//
//  MHMomentDetailControllerViewController.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/5/23.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHMomentDetailViewController.h"
#import "MHMomentHeaderView.h"
#import "MHMomentFooterView.h"
#import "MHMomentCommentCell.h"
#import "MHMomentAttitudesCell.h"
#import "MHMomentProfileView.h"
#import "MHMomentOperationMoreView.h"
#import "LCActionSheet.h"
#import "MHEmoticonManager.h"
#import "MHMomentHelper.h"
#import "MHMomentCommentToolView.h"
#import "ARSegmentControllerDelegate.h"
#import "MHViewController+MHCommonAlert.h"
#import "MHMomentViewModel.h"
#import "zhWallView.h"
#import "MHMomentDetailViewModel.h"
#import "MHshareRecent.h"
#import "MHAlertMessageView.h"
#import "UIScrollView+MHRefresh.h"

@interface MHMomentDetailViewController ()
@property (nonatomic, readonly, strong) MHMomentDetailViewModel *viewModel;

@property (nonatomic, readwrite, weak) MHMomentCommentToolView *commentToolView;

@property (nonatomic, readwrite, strong) NSIndexPath * selectedIndexPath;
/// 记录键盘高度
@property (nonatomic, readwrite, assign) CGFloat keyboardHeight;

@property(nonatomic, assign) BOOL inThisPage;

@end

@implementation MHMomentDetailViewController
@dynamic viewModel;

- (void)viewDidLoad {
    [[self.viewModel.requstRecentInfo execute:nil] subscribeNext:^(NSArray *array) {
            if (array.count > 0) {
                MHMoment *item =  [array lastObject];
                BOOL isAskDetail =  MHStringIsNotEmpty(item.recentQA.questionContent) && MHStringIsEmpty(item.recentQA.answerContent);
                if (isAskDetail && item.recentQA.answerUid == [MHHTTPService sharedInstance].currentUser.userId) {
                    
                    self.commentToolView.textView.placeholderText = @"回答";
                }
            }
    }];
    [super viewDidLoad];
    [self _setupSubViews];
//    self.tableView.mj_footer.hidden = (self.viewModel.comments.count % self.viewModel.perPage)?@1:@0;
    
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.inThisPage  = YES;
}

//-(void)bindViewModel
//{
//    [super bindViewModel];
//    @weakify(self);
//
//}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MHMomentHelper hideAllPopViewWithAnimated:NO];
    self.inThisPage  = false;
}


- (void)_setupSubViews{
    /// 配置tableView
    self.tableView.backgroundColor = [UIColor whiteColor];
    /// 固定高度-这样写比使用代理性能好，且使用代理会获取每次刷新数据会调用两次代理 ，苹果的bug
    self.tableView.sectionFooterHeight =  MHMomentFooterViewHeight;
    
    /// 个人信息view
    //    MHMomentProfileView *tableHeaderView = [[MHMomentProfileView alloc] init];
    //    [tableHeaderView bindViewModel:self.viewModel.profileViewModel];
    //    self.tableHeaderView = tableHeaderView;
    //
    //    @weakify(self);
    //    /// 动态更新tableHeaderView的高度. PS:单纯的设置其高度无效的
    //    [[RACObserve(self.viewModel.profileViewModel, unread)
    //      distinctUntilChanged]
    //     subscribeNext:^(NSNumber * unread) {
    //         @strongify(self);
    //         tableHeaderView.mh_height = self.viewModel.profileViewModel.height;
    //         [self.tableView beginUpdates];  // 过度动画
    //         self.tableView.tableHeaderView = tableHeaderView;
    //         [self.tableView endUpdates];
    //     }];
    
    
    /// 这里设置下拉黑色的背景图
    UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:MH_SCREEN_BOUNDS];
    backgroundView.mh_size = MH_SCREEN_BOUNDS.size;
    backgroundView.image = MHImageNamed(@"wx_around-friends_bg_320x568");
    backgroundView.mh_y = -backgroundView.mh_height;
    [self.tableView addSubview:backgroundView];
    
    
    /// 添加评论View
    MHMomentCommentToolView *commentToolView = [[MHMomentCommentToolView alloc] init];
    self.commentToolView = commentToolView;
    [self.view addSubview:commentToolView];
    
    [commentToolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.height.mas_equalTo(60);
        make.bottom.equalTo(self.view).with.offset(0);
    }];
    @weakify(self);
//    RAC(self.tableView.mj_footer, hidden) = [[RACObserve(self.viewModel, comments)
//                                              deliverOnMainThread]
//                                             map:^(NSArray *dataSource) {
//                                                 @strongify(self)
//                                                 NSUInteger count = dataSource.count;
//                                                 /// 无数据，默认隐藏mj_footer
//                                                 if (count == 0) return @1;
//                                                 
//                                                 if (self.viewModel.shouldEndRefreshingWithNoMoreData) return @(0);
//                                                 if (self.viewModel.comments.count < self.viewModel.perPage && self.viewModel.page) return @(1);
//                                                 /// because of
//                                                 return (count % self.viewModel.perPage)?@1:@0;
//                                             }];
}


- (void)bindViewModel{
    [super bindViewModel];
    
    /// ... 事件处理...
    /// 全文/收起
    @weakify(self);
    [[self.viewModel.reloadSectionSubject deliverOnMainThread] subscribeNext:^(NSNumber * section) {
        @strongify(self);
        /// 局部刷新 (内部已更新子控件的尺寸，这里只做刷新)
        /// 这个刷新会有个奇怪的动画
        [UIView performWithoutAnimation:^{
            [self.tableView reloadSection:section.integerValue withRowAnimation:UITableViewRowAnimationNone];
        }];
    }];
    
   
    [RACObserve(self.viewModel, hiddenFooter) subscribeNext:^(NSNumber *nuber) {
        @strongify(self);
        self.tableView.mj_footer.hidden = [nuber boolValue];
    }];
    
    [[self.viewModel.reloadDataSubject deliverOnMainThread] subscribeNext:^(NSNumber * section) {
        @strongify(self);
        [self.tableView reloadData];
    }];
    /// 评论
    [[self.viewModel.commentSubject deliverOnMainThread] subscribeNext:^(NSNumber * section) {
        @strongify(self);
        /// 记录选中的Section 这里设置Row为-1 以此来做判断
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:-1 inSection:section.integerValue];
        /// 显示评论
        [self _commentOrReplyWithItemViewModel:self.viewModel.dataSource[section.integerValue] indexPath:indexPath];
    }];
    
    /// 点击手机号码
//    [[self.viewModel.phoneSubject deliverOnMainThread] subscribeNext:^(NSString * phoneNum) {
//        @strongify(self);
//        LCActionSheet *sheet = [LCActionSheet sheetWithTitle:[NSString stringWithFormat:@"%@可能是一个电话号码，你可以",phoneNum] cancelButtonTitle:@"取消" clicked:^(LCActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
//            if (buttonIndex == 0) return ;
//        } otherButtonTitles:@"呼叫",@"复制号码",@"添加到手机通讯录", nil];
//        [sheet show];
//
//    }];
    
    
    
    
    
    /// 监听键盘 高度
    /// 监听按钮
    [[[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillChangeFrameNotification object:nil] takeUntil:self.rac_willDeallocSignal ]
      deliverOnMainThread]
     subscribeNext:^(NSNotification * notification) {
         @strongify(self);
         @weakify(self);
         [self mh_convertNotification:notification completion:^(CGFloat duration, UIViewAnimationOptions options, CGFloat keyboardH) {
             @strongify(self);
             
             //只在当前页面执行这个逻辑
                          if (!self.inThisPage) {
                              return;
                          }
             
             
             
             if (keyboardH <= 0) {
                 keyboardH = 0; //-1 * self.commentToolView.mh_height;
             }
             self.keyboardHeight = keyboardH;
             /// 全局记录keyboardH
             AXAppDelegate.sharedDelegate.showKeyboard = (keyboardH > 0);
             // bottomToolBar距离底部的高
             [self.commentToolView mas_updateConstraints:^(MASConstraintMaker *make) {
                 
#warning 特殊处理 commentToolView；
                 //                 make.bottom.equalTo(self.view).with.offset(-1 *keyboardH + 50 );
                 
                 make.bottom.equalTo(self.view).with.offset(-1 *keyboardH);
                 
             }];
             
             //特殊处理详情页
             if (self.viewModel.isDetail) {
                 if (!self.selectedIndexPath) {
                     [self.viewModel.commentSubject sendNext:@(0)];
                 }
             }
             
             // 执行动画
             [UIView animateWithDuration:duration delay:0.0f options:options animations:^{
                 // 如果是Masonry或者autoLayout UITextField或者UITextView 布局 必须layoutSubviews，否则文字会跳动
                 [self.view layoutSubviews];
                 /// 滚动表格
                 [self _scrollTheTableViewForComment];
             } completion:nil];
         }];
     }];
    
    
    //// 监听commentToolView的高度变化
    [[RACObserve(self.commentToolView, toHeight) distinctUntilChanged] subscribeNext:^(NSNumber * toHeight) {
        @strongify(self);
        if (toHeight.floatValue < MHMomentCommentToolViewMinHeight) return ;
        /// 更新CommentView的高度
        [self.commentToolView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(toHeight);
        }];
        [UIView animateWithDuration:.25f animations:^{
            // 适当时候更新布局
            [self.view layoutSubviews];
            /// 滚动表格
            [self _scrollTheTableViewForComment];
        }];
    }];
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath{
    return [MHMomentContentCell cellWithTableView:tableView];
}

- (void)configureCell:(MHMomentContentCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object{
    MHMomentItemViewModel *itemViewModel =  self.viewModel.dataSource[indexPath.section];
    id model = itemViewModel.dataSource[indexPath.row];
    [cell bindViewModel:model];
}

#pragma mark - 初始化道导航栏

/// PS:这里复写了 MHTableViewController 里面的UITableViewDelegate和UITableViewDataSource的方法，所以大家不需要过多关注 MHTableViewController的里面的UITableViewDataSource方法
#pragma mark - UITableViewDataSource & UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.viewModel.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MHMomentItemViewModel *itemViewModel =  self.viewModel.dataSource[section];
    return itemViewModel.dataSource.count;
}

// custom view for header. will be adjusted to default or specified header height
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    MHMomentHeaderView *headerView = [MHMomentHeaderView headerViewWithTableView:tableView];
    /// 传递section 后期需要用到
    headerView.section = section;
    MHMomentItemViewModel *itemViweModel = self.viewModel.dataSource[section];
    [headerView bindViewModel:self.viewModel.dataSource[section]];
    @weakify(self)
    
    //分享
    //分享
    [[itemViweModel.shareMomentCommand executionSignals].switchToLatest subscribeNext:^(MHshareRecent *shareModel) {
        @strongify(self);
        self.zh_popupController = [zhPopupController new];
        self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
        zhWallView *wallView =  [self wallView];
        shareModel.shareMoment = itemViweModel.moment;
        wallView.section = (int) section;
        wallView.models = [self shareWallModelsWithSection:wallView.section shareModel:shareModel];
        [wallView autoAdjustFitHeight];
        @weakify(self);
        wallView.didClickFooter = ^(zhWallView * _Nonnull sheetView) {
            @strongify(self);
            [self.zh_popupController dismiss];
        };
        [self.zh_popupController presentContentView:wallView];
        
    }];
    
    
    
    
    [[itemViweModel.showBottomMenuViewCommand executionSignals] subscribeNext:^(id x) {
        @strongify(self);
        self.zh_popupController = [zhPopupController new];
        self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
        zhWallView *wallView =  [self wallView];
        wallView.section = (int) section;
        wallView.models = [self wallModelsWithSection:wallView.section itemViweModel:itemViweModel];
        [wallView autoAdjustFitHeight];
        @weakify(self);
        wallView.didClickFooter = ^(zhWallView * _Nonnull sheetView) {
            @strongify(self);
            [self.zh_popupController dismiss];
        };
        [self.zh_popupController presentContentView:wallView];
        
    }];
    
    return headerView;
}


- (NSArray *)shareWallModelsWithSection:(int )seciton shareModel:(MHshareRecent *)recent{
    
    
    __weak __typeof(self)weakSelf = self;
    VoidBlock_id_int shareFriend =  ^(UIButton *button, int index) {
        
        [weakSelf.zh_popupController dismiss];
         [MHMomentHelper shareWithSharRecent:recent shareType:MHCirclShareTypeWeChat];
        
    };
    
    VoidBlock_id_int shareTimeLine =  ^(UIButton *button, int index) {
        [weakSelf.zh_popupController dismiss];
         [MHMomentHelper shareWithSharRecent:recent shareType:MHCirclShareTypeWeChatTimeLine];
    };
    NSArray *arr1;
    if (recent.shareMoment.shareTimeLine) {
        arr1 = @[
                 
                 @{titleKey   : @"微信朋友圈",
                   imgNameKey : @"icon_share_timeline",
                   excutesCustomBlock: shareTimeLine,
                   
                   },
                 ];
    }else
    {
        arr1 = @[
                 
                 @{titleKey   : @"微信",
                   imgNameKey : @"icon_share_wechat",
                   excutesCustomBlock: shareFriend,
                   
                   },
                 
                 @{titleKey   : @"微信朋友圈",
                   imgNameKey : @"icon_share_timeline",
                   excutesCustomBlock: shareTimeLine,
                   
                   },
                 ];
    }
    
    
    NSMutableArray *array1 = [NSMutableArray array];
    for (NSDictionary *dict in arr1) {
        NSString *text = [dict objectForKey:titleKey];
        NSString *imgName = [dict objectForKey:imgNameKey];
        NSString *seleImage = [dict objectForKey:selImageName];
        VoidBlock_id_int excutBlock = [dict objectForKey:excutesCustomBlock];
        BOOL isSeleted = [[dict objectForKey:modelSelected] boolValue];
        int index =  [arr1 indexOfObject:dict];
        [array1 addObject:[zhWallItemModel  modelWithImage:[UIImage imageNamed:imgName] selectImage:[UIImage imageNamed:seleImage] isSelect:isSeleted text:text clickBlock:excutBlock]];
    }
    
    return [NSMutableArray arrayWithObjects:array1, nil];
}



- (NSArray *)wallModelsWithSection:(int )seciton itemViweModel:(MHMomentItemViewModel * )itemViweModel{
    BOOL isTop = itemViweModel.moment.isTop;
    BOOL isEssence = itemViweModel.moment.isEssence;
    BOOL isCollection = itemViweModel.moment.isHaveCollect;
    __weak __typeof(self)weakSelf = self;
    VoidBlock_id_int top =  ^(UIButton *button, int index) {
        
        if (isTop) {
            [weakSelf.viewModel.cancelTopMomentCommand execute:@(seciton)];
        }else
        {
            [weakSelf.viewModel.topMomentCommand execute:@(seciton)];
        }
        
        [weakSelf.zh_popupController dismiss];
    };
    
    VoidBlock_id_int collection =  ^(UIButton *button, int index) {
        @weakify(self);
       
        [[itemViweModel.collectionCommand execute: @{@"isCollection":@(isCollection),@"section":@(seciton)}] subscribeNext:^(id x) {
            @strongify(self);
            itemViweModel.moment.isHaveCollect = !isCollection;
        
        }];
        [weakSelf.zh_popupController dismiss];
    };
    
    VoidBlock_id_int repo =  ^(UIButton *button, int index) {
        [weakSelf.viewModel.repoCommand execute:@(seciton)];
        [weakSelf.zh_popupController dismiss];
    };
    
    VoidBlock_id_int delete =  ^(UIButton *button, int index) {
        
        
        [self showAlertViewControllerWithTitle:@"删除该主题" content:@"该主题删除后将不会显示在主题列表?" comfirmblock:^{
            [weakSelf.viewModel.delMomentCommand execute:@(seciton)];
                        [weakSelf.zh_popupController dismiss];
        } dissMissBlock:^{
            [weakSelf.zh_popupController dismiss];
        }];
        
//        self.zh_popupController = [zhPopupController new];
//        MHAlertMessageView *alert = [[MHAlertMessageView alloc] initWihtTitle:@"删除该主题" message:@"确定删除该主题?"];
//        [alert.dissMissButton setTitle:@"取消" forState:0];
//        [alert.comfirmButton setTitle:@"确定" forState:0];
//        alert.mh_width = self.view.mh_width * 0.8;
//        __weak __typeof(self)weakSelf = self;
//        [alert.dissMissButton bk_whenTapped:^{
//            [weakSelf.zh_popupController dismiss];
//        }];
//        [alert.comfirmButton bk_whenTapped:^{
//             [weakSelf.viewModel.delMomentCommand execute:@(seciton)];
//            [weakSelf.zh_popupController dismiss];
//        }];
//        [self.zh_popupController presentContentView:alert duration:0.25 springAnimated:YES];
        
    };
    VoidBlock_id_int essence =  ^(UIButton *button, int index) {
        if (isEssence) {
            
            [weakSelf.viewModel.cancelEssenceMomentCommand execute:@(seciton)];
        }else
        {
            [weakSelf.viewModel.setEssenceMomentCommand execute:@(seciton)];
        }
        [weakSelf.zh_popupController dismiss];
    };
    NSDictionary *topDic =   @{titleKey   : isTop ? @"取消置顶" : @"置顶",
                               imgNameKey : @"cirle_more_topnor",
                               selImageName:@"circle_more_topsel",
                               modelSelected: @(isTop),
                               excutesCustomBlock: top,
                               };
    
    NSDictionary *essenceDic =  @{titleKey   : isEssence ? @"取消精华":@"精华",
                                  imgNameKey : @"circle_more_jhnor",
                                  selImageName:@"circle_more_jhsel",
                                  modelSelected: @(isEssence),
                                  excutesCustomBlock: essence,
                                  };
    
    NSDictionary *repoDic =  @{titleKey   : @"举报",
                               imgNameKey : @"circle_repo_normal",
                               excutesCustomBlock: repo,
                               };
    
    NSDictionary *delDic =   @{titleKey   : @"删除",
                               imgNameKey : @"circle_more_del",
                               excutesCustomBlock: delete,
                               };
    
    NSDictionary *collecitonDic =   @{titleKey   : isCollection ? @"取消收藏" : @"收藏",
                                      imgNameKey : @"circle_collectionnor",
                                      selImageName:@"circle_collectionsel",
                                      modelSelected: @(isCollection),
                                      excutesCustomBlock: collection,
                                      };
    
    MHMomentMemberIdentity identity = itemViweModel.moment.identType;//MHMemberIdentity([AXAppDelegate sharedDelegate].currentCircleInfo.ownerUid, itemViweModel.moment.publishUserId, [MHHTTPService sharedInstance].currentUser.userId);
    
    NSArray *arr1 = @[];
    NSArray *arr2 = @[];
    if (itemViweModel.moment.publishUserId == [MHHTTPService sharedInstance].currentUser.userId) {
        arr1 = @[collecitonDic,repoDic,delDic];
    }else
    {
        arr1 = @[collecitonDic,repoDic];
    }
//    if (identity == MHMomentOwnerToSelf) {
//        arr1 =  @[topDic, essenceDic,collecitonDic,delDic];
//        //        arr2 = @[];
//    }else if(identity == MHMomentOwnerToMember)
//    {
//        arr1 =  @[topDic, essenceDic,collecitonDic,repoDic];
//        arr2 = @[delDic];
//    }else if(identity == MHMomentMemberToSelf)
//    {
//        arr1 =  @[];
//        arr2 = @[collecitonDic,delDic];
//    }else{
//        arr2 = @[collecitonDic,repoDic];
//    }
    
    NSMutableArray *array1 = [NSMutableArray array];
    for (NSDictionary *dict in arr1) {
        NSString *text = [dict objectForKey:titleKey];
        NSString *imgName = [dict objectForKey:imgNameKey];
        NSString *seleImage = [dict objectForKey:selImageName];
        BOOL isSeleted = [[dict objectForKey:modelSelected] boolValue];
        VoidBlock_id_int excutBlock = [dict objectForKey:excutesCustomBlock];
        int index =  [arr1 indexOfObject:dict];
        [array1 addObject:[zhWallItemModel  modelWithImage:[UIImage imageNamed:imgName] selectImage:[UIImage imageNamed:seleImage] isSelect:isSeleted text:text clickBlock:excutBlock]];
    }
    NSMutableArray *array2 = [NSMutableArray array];
    for (NSDictionary *dict in arr2) {
        NSString *text = [dict objectForKey:titleKey];
        NSString *imgName = [dict objectForKey:imgNameKey];
        NSString *seleImage = [dict objectForKey:selImageName];
        int index =  [arr2 indexOfObject:dict];
        VoidBlock_id_int excutBlock = [dict objectForKey:excutesCustomBlock];
        BOOL isSeleted = [[dict objectForKey:modelSelected] boolValue];
        [array2 addObject:[zhWallItemModel  modelWithImage:[UIImage imageNamed:imgName] selectImage:[UIImage imageNamed:seleImage] isSelect:isSeleted text:text clickBlock:excutBlock]];
    }
    NSMutableArray *resultArray = [NSMutableArray array];
    
    if (array1.count) {
        [resultArray appendObject:array1];
    }
    if (array2.count) {
        [resultArray appendObject:array2];
    }
    
    return resultArray;
}

//处理详情被遮挡

-(UIEdgeInsets)contentInset
{
    return UIEdgeInsetsMake(MH_APPLICATION_TOP_BAR_HEIGHT, 0, 60, 0);
}
// custom view for footer. will be adjusted to default or specified footer height
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    MHMomentFooterView *footerView = [MHMomentFooterView footerViewWithTableView:tableView];
    footerView.divider.hidden = YES;
    return footerView;
}

/// 点击Cell的事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    /// 先取出该section的说说
    MHMomentItemViewModel *itemViweModel = self.viewModel.dataSource[section];
    /// 然后取出该 row 的评论Or点赞
    MHMomentContentItemViewModel *contentItemViewModel = itemViweModel.dataSource[row];
    /// 去掉点赞
    if ([contentItemViewModel isKindOfClass:MHMomentAttitudesItemViewModel.class]) {
        [self.commentToolView mh_resignFirstResponder];
        return;
    }
    
    /// 判断是否是自己的评论  或者 回复
    MHMomentCommentItemViewModel *commentItemViewModel = (MHMomentCommentItemViewModel *)contentItemViewModel;
    
    NSString *idString = self.viewModel.services.client.currentUser.idstr;
    if ([commentItemViewModel.comment.fromUser.idstr isEqualToString: self.viewModel.services.client.currentUser.idstr]) {
        /// 关掉键盘
        [self.commentToolView  mh_resignFirstResponder];
        
        /// 自己评论的活回复他人
        @weakify(self);
        LCActionSheet *sheet = [LCActionSheet sheetWithTitle:nil cancelButtonTitle:@"取消" clicked:^(LCActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
            if (buttonIndex == 0) return ;
            @strongify(self);
            /// 删除数据源
            [self.viewModel.delCommentCommand execute:indexPath];
            
        } otherButtonTitles:@"删除", nil];
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
        sheet.destructiveButtonIndexSet = indexSet;
        [sheet show];
        return;
    }
    
    MHLogFunc;
    /// 键盘已经显示 你就先关掉键盘
    if (MHSharedAppDelegate.isShowKeyboard) {
        [self.commentToolView mh_resignFirstResponder];
        return;
    }
    
    /// 评论
    [self _commentOrReplyWithItemViewModel:contentItemViewModel indexPath:indexPath];
}


// custom view for cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    // fetch object 报错 why???
    //    id object  = [self.viewModel.dataSource[indexPath.section] dataSource][indexPath.row];
    MHMomentItemViewModel *itemViewModel = self.viewModel.dataSource[indexPath.section];
    id object = itemViewModel.dataSource[indexPath.row];
    /// bind model
    [self configureCell:cell atIndexPath:indexPath withObject:(id)object];
    return cell;
}

/// 设置高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    MHMomentItemViewModel *itemViewModel = self.viewModel.dataSource[section];
    /// 这里每次刷新都会走两次！！！ Why？？？
    return itemViewModel.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MHMomentItemViewModel *itemViewModel =  self.viewModel.dataSource[indexPath.section];
    /// 这里用 id 去指向（但是一定要确保取出来的模型有 `cellHeight` 属性 ，否则crash）
    id model = itemViewModel.dataSource[indexPath.row];
    return [model cellHeight];
}

/// 监听滚动到顶部
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView{
    /// 这里下拉刷新
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    /// 处理popView
    [MHMomentHelper hideAllPopViewWithAnimated:NO];
}

-(void)rightButtonClick
{
    if ([self.viewModel.rightTitle containsString:@"圈子"]) {
        [MHMomentHelper enterOrJionCircleWithViewModel:self.viewModel];
    }
}

#pragma mark - 辅助方法
- (void)_commentOrReplyWithItemViewModel:(id)itemViewModel indexPath:(NSIndexPath *)indexPath{
    /// 传递数据 (生成 replyItemViewModel)
    MHMomentReplyItemViewModel *viewModel = [[MHMomentReplyItemViewModel alloc] initWithItemViewModel:itemViewModel];
    viewModel.section = indexPath.section;
    viewModel.commentCommand = self.viewModel.commentCommand;
    self.selectedIndexPath = indexPath; /// 记录indexPath
    [self.commentToolView bindViewModel:viewModel];
    /// 键盘弹起
    [self.commentToolView  mh_becomeFirstResponder];
}

/// 评论的时候 滚动tableView，计算差值优化
- (void)_scrollTheTableViewForComment{
    CGRect rect = CGRectZero;
    CGRect rect1 = CGRectZero;
    if (self.selectedIndexPath.row == -1 || !self.selectedIndexPath) {
        if (self.viewModel.dataSource.count <= 0) {
            return;
        }
        rect = [self.tableView rectForFooterInSection:self.selectedIndexPath.section];
        rect1 = [self.tableView convertRect:rect toViewOrWindow:nil];
    }else{
        /// 回复
        /// 获取整个尾部section对应的尺寸 获取的rect是相当于tableView的尺寸
        rect = [self.tableView rectForRowAtIndexPath:self.selectedIndexPath];
        /// 将尺寸转化到window的坐标系 （关键点）
        rect1 = [self.tableView convertRect:rect toViewOrWindow:nil];
    }
//    if (self.keyboardHeight > 0 && self.selectedIndexPath && self.keyboardHeight != -60) { /// 键盘抬起 才允许滚动
//        /// 这个就是你需要滚动差值
//        CGFloat delta = self.commentToolView.mh_top - rect1.origin.y - rect1.size.height;
//        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentOffset.y-delta) animated:NO];
//    }
}



@end
